package pku;

import snappy.Snappy;
import java.io.IOException;
import java.io.RandomAccessFile;


public class MessageWriter {

    private RandomAccessFile raf;

    public static final int defaultLen = Constants.MSGAP;

    private byte[] bytes = new byte[defaultLen + Constants.MSGlEN];

    private int count;

    private byte[] wBytes = new byte[defaultLen + Constants.MSGlEN];


    public MessageWriter(String dir) throws IOException {
        raf = new RandomAccessFile(dir, "rw");
    }


    private void put(byte a) {

        bytes[count++] = (byte) (a & 0xff);
    }

    private void put(byte[] bs) {
        int a = bs.length;
        bytes[count++] = (byte) a;
        bytes[count++] = (byte) (a>>8);
        bytes[count++] = (byte) (a>>16);
        bytes[count++] = (byte) (a>>24);

        System.arraycopy(bs, 0, bytes, count, bs.length);
        count += bs.length;

    }

    public void write(DefaultMessage message) throws IOException, InstantiationException {
        DefaultKeyValue h = (DefaultKeyValue) message.headers();
        byte tsize = (byte) (((byte) h.num));

        put(tsize);
        for (int i = 0; i < h.num; i++) {
            put(h.pos[i]);
            put(h.values[i]);
        }

        byte[] body = ((DefaultMessage) message).getBody();
        put(body);

        if (count >= defaultLen) {

            int clen = Snappy.compress(bytes, 0, count, wBytes, 0);

            raf.writeShort(clen);
            raf.write(wBytes, 0, clen);
            this.count = 0;

        }
    }

    public void close() throws IOException {
        if (this.count > 0) {
            int clen = Snappy.compress(bytes, 0, count, wBytes, 0);
            raf.writeShort(clen);
            raf.write(wBytes, 0, clen);
        }
        raf.writeShort(0);

        raf.close();
    }
}
